<?php

namespace App\Services;

use App\Models\Follow;
use App\Models\User;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\DB;

class FollowService
{
    /**
     * 关注用户
     */
    public function follow(User $follower, User $following): Follow
    {
        return DB::transaction(function () use ($follower, $following) {
            // 不能关注自己
            if ($follower->id === $following->id) {
                throw new \Exception('不能关注自己');
            }

            // 检查是否已经关注
            $existingFollow = Follow::where('follower_id', $follower->id)
                ->where('following_id', $following->id)
                ->first();

            if ($existingFollow) {
                throw new \Exception('您已关注该用户');
            }

            // 创建关注关系
            $follow = Follow::create([
                'follower_id' => $follower->id,
                'following_id' => $following->id,
            ]);

            // 更新统计（确保字段存在且不为负数）
            if ($following->followers_count !== null) {
                $following->increment('followers_count');
            }
            if ($follower->following_count !== null) {
                $follower->increment('following_count');
            }

            return $follow;
        });
    }

    /**
     * 取消关注
     */
    public function unfollow(User $follower, User $following): bool
    {
        return DB::transaction(function () use ($follower, $following) {
            $follow = Follow::where('follower_id', $follower->id)
                ->where('following_id', $following->id)
                ->first();

            if (! $follow) {
                throw new \Exception('您未关注该用户');
            }

            $deleted = $follow->delete();

            if ($deleted) {
                // 更新统计（确保字段存在且不为负数）
                if ($following->followers_count !== null && $following->followers_count > 0) {
                    $following->decrement('followers_count');
                }
                if ($follower->following_count !== null && $follower->following_count > 0) {
                    $follower->decrement('following_count');
                }
            }

            return $deleted;
        });
    }

    /**
     * 获取用户的关注列表
     */
    public function getFollowingList(User $user, int $perPage = 20): LengthAwarePaginator
    {
        return $user->followings()
            ->with(['followers', 'posts'])
            ->paginate($perPage);
    }

    /**
     * 获取用户的粉丝列表
     */
    public function getFollowersList(User $user, int $perPage = 20): LengthAwarePaginator
    {
        return $user->followers()
            ->with(['followings', 'posts'])
            ->paginate($perPage);
    }

    /**
     * 判断用户A是否关注了用户B
     */
    public function isFollowing(User $follower, User $following): bool
    {
        return $follower->isFollowing($following);
    }
}
